// 格式化时间
export const formatDate = (timestamp, format = "YYYY-MM-DD HH:mm:ss") => {
  if (!timestamp) return "";

  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return format
    .replace("YYYY", year)
    .replace("MM", month)
    .replace("DD", day)
    .replace("HH", hours)
    .replace("mm", minutes)
    .replace("ss", seconds);
};

// 友好的时间显示
export const timeAgo = (timestamp) => {
  if (!timestamp) return "";

  const seconds = Math.floor((Date.now() - timestamp) / 1000);

  // 小于1分钟
  if (seconds < 60) {
    return "刚刚";
  }

  // 小于1小时
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) {
    return `${minutes}分钟前`;
  }

  // 小于1天
  const hours = Math.floor(minutes / 60);
  if (hours < 24) {
    return `${hours}小时前`;
  }

  // 小于1个月
  const days = Math.floor(hours / 24);
  if (days < 30) {
    return `${days}天前`;
  }

  // 小于1年
  const months = Math.floor(days / 30);
  if (months < 12) {
    return `${months}个月前`;
  }

  // 大于1年
  const years = Math.floor(months / 12);
  return `${years}年前`;
};

// 将HTML内容转换为纯文本 (摘要)
export const htmlToText = (html, maxLength = 100) => {
  if (!html) return "";

  // 移除HTML标签
  const text = html.replace(/<[^>]+>/g, "");

  // 裁剪文本
  if (text.length > maxLength) {
    return text.substring(0, maxLength) + "...";
  }

  return text;
};

// 显示加载提示
export const showLoading = (title = "加载中") => {
  uni.showLoading({
    title,
    mask: true,
  });
};

// 隐藏加载提示
export const hideLoading = () => {
  uni.hideLoading();
};

// 显示成功提示
export const showSuccess = (title = "操作成功", duration = 1500) => {
  uni.showToast({
    title,
    icon: "none",
    duration,
  });
};

// 显示失败提示
export const showError = (title = "操作失败", duration = 1500) => {
  uni.showToast({
    title,
    icon: "none",
    duration,
  });
};

// 显示确认对话框
export const showConfirm = (content, title = "提示") => {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else {
          resolve(false);
        }
      },
      fail: () => {
        resolve(false);
      },
    });
  });
};

// 获取缓存数据
export const getCache = (key, defaultValue = null) => {
  try {
    const value = uni.getStorageSync(key);
    return value ? JSON.parse(value) : defaultValue;
  } catch (e) {
    return defaultValue;
  }
};

// 设置缓存数据
export const setCache = (key, value, expire = 0) => {
  try {
    const data = {
      value,
      expire: expire > 0 ? Date.now() + expire * 1000 : 0,
    };
    uni.setStorageSync(key, JSON.stringify(data));
    return true;
  } catch (e) {
    return false;
  }
};

// 清除缓存数据
export const removeCache = (key) => {
  try {
    uni.removeStorageSync(key);
    return true;
  } catch (e) {
    return false;
  }
};

// MD5加密函数
export const md5 = (str) => {
  // 这是一个简化版的MD5实现，生产环境请使用成熟的库
  function d(n, t) {
    var r = (65535 & n) + (65535 & t);
    return (((n >> 16) + (t >> 16) + (r >> 16)) << 16) | (65535 & r);
  }
  function f(n, t, r, e, o, u) {
    return d(((c = d(d(t, n), d(e, u))) << (f = o)) | (c >>> (32 - f)), r);
    var c, f;
  }
  function l(n, t, r, e, o, u, c) {
    return f((t & r) | (~t & e), n, t, o, u, c);
  }
  function g(n, t, r, e, o, u, c) {
    return f((t & e) | (r & ~e), n, t, o, u, c);
  }
  function v(n, t, r, e, o, u, c) {
    return f(t ^ r ^ e, n, t, o, u, c);
  }
  function m(n, t, r, e, o, u, c) {
    return f(r ^ (t | ~e), n, t, o, u, c);
  }
  function i(n, t) {
    var r, e, o, u;
    (n[t >> 5] |= 128 << t % 32), (n[14 + (((t + 64) >>> 9) << 4)] = t);
    for (
      var c = 1732584193, f = -271733879, i = -1732584194, a = 271733878, h = 0;
      h < n.length;
      h += 16
    )
      (c = l((r = c), (e = f), (o = i), (u = a), n[h], 7, -680876936)),
        (a = l(a, c, f, i, n[h + 1], 12, -389564586)),
        (i = l(i, a, c, f, n[h + 2], 17, 606105819)),
        (f = l(f, i, a, c, n[h + 3], 22, -1044525330)),
        (c = l(c, f, i, a, n[h + 4], 7, -176418897)),
        (a = l(a, c, f, i, n[h + 5], 12, 1200080426)),
        (i = l(i, a, c, f, n[h + 6], 17, -1473231341)),
        (f = l(f, i, a, c, n[h + 7], 22, -45705983)),
        (c = l(c, f, i, a, n[h + 8], 7, 1770035416)),
        (a = l(a, c, f, i, n[h + 9], 12, -1958414417)),
        (i = l(i, a, c, f, n[h + 10], 17, -42063)),
        (f = l(f, i, a, c, n[h + 11], 22, -1990404162)),
        (c = l(c, f, i, a, n[h + 12], 7, 1804603682)),
        (a = l(a, c, f, i, n[h + 13], 12, -40341101)),
        (i = l(i, a, c, f, n[h + 14], 17, -1502002290)),
        (c = g(
          c,
          (f = l(f, i, a, c, n[h + 15], 22, 1236535329)),
          i,
          a,
          n[h + 1],
          5,
          -165796510
        )),
        (a = g(a, c, f, i, n[h + 6], 9, -1069501632)),
        (i = g(i, a, c, f, n[h + 11], 14, 643717713)),
        (f = g(f, i, a, c, n[h], 20, -373897302)),
        (c = g(c, f, i, a, n[h + 5], 5, -701558691)),
        (a = g(a, c, f, i, n[h + 10], 9, 38016083)),
        (i = g(i, a, c, f, n[h + 15], 14, -660478335)),
        (f = g(f, i, a, c, n[h + 4], 20, -405537848)),
        (c = g(c, f, i, a, n[h + 9], 5, 568446438)),
        (a = g(a, c, f, i, n[h + 14], 9, -1019803690)),
        (i = g(i, a, c, f, n[h + 3], 14, -187363961)),
        (f = g(f, i, a, c, n[h + 8], 20, 1163531501)),
        (c = g(c, f, i, a, n[h + 13], 5, -1444681467)),
        (a = g(a, c, f, i, n[h + 2], 9, -51403784)),
        (i = g(i, a, c, f, n[h + 7], 14, 1735328473)),
        (c = v(
          c,
          (f = g(f, i, a, c, n[h + 12], 20, -1926607734)),
          i,
          a,
          n[h + 5],
          4,
          -378558
        )),
        (a = v(a, c, f, i, n[h + 8], 11, -2022574463)),
        (i = v(i, a, c, f, n[h + 11], 16, 1839030562)),
        (f = v(f, i, a, c, n[h + 14], 23, -35309556)),
        (c = v(c, f, i, a, n[h + 1], 4, -1530992060)),
        (a = v(a, c, f, i, n[h + 4], 11, 1272893353)),
        (i = v(i, a, c, f, n[h + 7], 16, -155497632)),
        (f = v(f, i, a, c, n[h + 10], 23, -1094730640)),
        (c = v(c, f, i, a, n[h + 13], 4, 681279174)),
        (a = v(a, c, f, i, n[h], 11, -358537222)),
        (i = v(i, a, c, f, n[h + 3], 16, -722521979)),
        (f = v(f, i, a, c, n[h + 6], 23, 76029189)),
        (c = v(c, f, i, a, n[h + 9], 4, -640364487)),
        (a = v(a, c, f, i, n[h + 12], 11, -421815835)),
        (i = v(i, a, c, f, n[h + 15], 16, 530742520)),
        (c = m(
          c,
          (f = v(f, i, a, c, n[h + 2], 23, -995338651)),
          i,
          a,
          n[h],
          6,
          -198630844
        )),
        (a = m(a, c, f, i, n[h + 7], 10, 1126891415)),
        (i = m(i, a, c, f, n[h + 14], 15, -1416354905)),
        (f = m(f, i, a, c, n[h + 5], 21, -57434055)),
        (c = m(c, f, i, a, n[h + 12], 6, 1700485571)),
        (a = m(a, c, f, i, n[h + 3], 10, -1894986606)),
        (i = m(i, a, c, f, n[h + 10], 15, -1051523)),
        (f = m(f, i, a, c, n[h + 1], 21, -2054922799)),
        (c = m(c, f, i, a, n[h + 8], 6, 1873313359)),
        (a = m(a, c, f, i, n[h + 15], 10, -30611744)),
        (i = m(i, a, c, f, n[h + 6], 15, -1560198380)),
        (f = m(f, i, a, c, n[h + 13], 21, 1309151649)),
        (c = m(c, f, i, a, n[h + 4], 6, -145523070)),
        (a = m(a, c, f, i, n[h + 11], 10, -1120210379)),
        (i = m(i, a, c, f, n[h + 2], 15, 718787259)),
        (f = m(f, i, a, c, n[h + 9], 21, -343485551)),
        (c = d(c, r)),
        (f = d(f, e)),
        (i = d(i, o)),
        (a = d(a, u));
    return [c, f, i, a];
  }
  function a(n) {
    for (var t = "", r = 32 * n.length, e = 0; e < r; e += 8)
      t += String.fromCharCode((n[e >> 5] >>> e % 32) & 255);
    return t;
  }
  function h(n) {
    var t = [];
    for (t[(n.length >> 2) - 1] = void 0, e = 0; e < t.length; e += 1) t[e] = 0;
    for (var r = 8 * n.length, e = 0; e < r; e += 8)
      t[e >> 5] |= (255 & n.charCodeAt(e / 8)) << e % 32;
    return t;
  }
  function e(n) {
    for (var t, r = "0123456789abcdef", e = "", o = 0; o < n.length; o += 1)
      (t = n.charCodeAt(o)), (e += r.charAt((t >>> 4) & 15) + r.charAt(15 & t));
    return e;
  }
  function r(n) {
    return unescape(encodeURIComponent(n));
  }
  function o(n) {
    return a(i(h((t = r(n))), 8 * t.length));
    var t;
  }
  function u(n, t) {
    return (function (n, t) {
      var r,
        e,
        o = h(n),
        u = [],
        c = [];
      for (
        u[15] = c[15] = void 0,
          16 < o.length && (o = i(o, 8 * n.length)),
          r = 0;
        r < 16;
        r += 1
      )
        (u[r] = 909522486 ^ o[r]), (c[r] = 1549556828 ^ o[r]);
      return (
        (e = i(u.concat(h(t)), 512 + 8 * t.length)), a(i(c.concat(e), 640))
      );
    })(r(n), r(t));
  }
  return e(o(str));
};

// 生成徽章URL
export const genMetal = (name, attr) => {
  if (attr !== undefined && attr !== "") {
    attr = "&" + attr;
  } else {
    attr = "";
  }

  // 获取认证信息，尝试不同的键名
  const apiKey = uni.getStorageSync("fishpi_api_key") || "";

  // 添加apiKey作为认证参数
  return (
    "https://fishpi.cn/gen?ver=0.1&scale=0.79&txt=" +
    name +
    attr +
    (apiKey ? "&apiKey=" + apiKey : "")
  );
};

// 根据用户角色获取对应的角色图片
export const getRoleImage = (userRole, returnHTML = true) => {
  let imageUrl = "";

  switch (userRole) {
    case "管理员":
      imageUrl = "https://file.fishpi.cn/adminRole.png";
      break;
    case "OP":
      imageUrl = "https://file.fishpi.cn/opRole.png";
      break;
    case "纪律委员":
      imageUrl = "https://file.fishpi.cn/policeRole.png";
      break;
    case "超级会员":
      imageUrl = "https://file.fishpi.cn/svipRole.png";
      break;
    case "成员":
      imageUrl = "https://file.fishpi.cn/vipRole.png";
      break;
    default:
      imageUrl = "https://file.fishpi.cn/newRole.png";
      break;
  }

  // 返回HTML或纯URL
  if (returnHTML) {
    return `<img style="height: 24px;margin: 0px;vertical-align: middle;" src="${imageUrl}"/>`;
  }

  return imageUrl;
};
